<template>
    <div class="comment-list-container">
        <div v-loading="loading">
            <el-empty v-if="comments?.length === 0 && !loading" description="暂无评论" />

            <template v-else>
                <div v-for="comment in comments" :key="comment.id">
                    <characterCommentCard :comment="comment" :show-delete="comment.user_id === userId" @update-comment="handleUpdateComment"
                        @delete-comment="handleDeleteComment" />
                </div>

                <el-pagination v-if="pagination.total > pagination.limit" background layout="prev, pager, next"
                    :total="pagination.total" :page-size="pagination.limit" :current-page="pagination.page"
                    @current-change="handlePageChange" />
            </template>
        </div>

        <!-- 悬浮发布按钮 -->
        <div class="floating-action" @click="showCommentDialog = true">
            <el-icon :size="28">
                <Edit />
            </el-icon>
        </div>

        <!-- 评论对话框 -->
        <el-dialog v-model="showCommentDialog" title="发表评论" width="80%" :close-on-click-modal="false">
            <el-input v-model="newComment" type="textarea" :rows="3" placeholder="输入你的评论..." maxlength="200"
                show-word-limit />
            <template #footer>
                <el-button @click="showCommentDialog = false">取消</el-button>
                <el-button type="primary" @click="handleSubmitComment" :loading="submitting">
                    提交
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { Edit }from '@element-plus/icons-vue'
import { charactersCommentAPI } from '@/api/charactersComments';
import characterCommentCard from '@/components/characterCommentCard/index.vue';
import { decrypt } from '@/utils/crypto'

const props = defineProps({
    characterId: {
        type: [Number, String],
        required: true
    }
});

const comments = ref([]);
const loading = ref(false);
const showCommentDialog = ref(false);
const newComment = ref('');
const submitting = ref(false);
const userId = ref(JSON.parse(decrypt(localStorage.getItem('user')))?.user_id || null);

const pagination = ref({
    page: 1,
    limit: 10,
    total: 0
});

const loadComments = async () => {
    try {
        loading.value = true;
        const { data } = await charactersCommentAPI.getCommentsByCharacterId(props.characterId, {
            page: pagination.value.page,
            limit: pagination.value.limit
        });
        comments.value = data || []; 
    } catch (error) {
        ElMessage.error(error.response?.data?.message || '加载评论失败');
    } finally {
        loading.value = false;
    }
};

const handlePageChange = (newPage) => {
    pagination.value.page = newPage;
    loadComments();
};

const handleSubmitComment = async () => {
    if (!newComment.value.trim()) {
        ElMessage.warning('评论内容不能为空');
        return;
    }

    try {
        submitting.value = true;
        await charactersCommentAPI.createComment({
            content: newComment.value,
            characterId: props.characterId
        });

        ElMessage.success('评论成功');
        showCommentDialog.value = false;
        newComment.value = '';
        // 刷新评论列表
        if (pagination.value.page === 1) {
            await loadComments();
        } else {
            pagination.value.page = 1;
        }
    } catch (error) {
        ElMessage.error(error.response?.data?.message || '评论失败');
    } finally {
        submitting.value = false;
    }
};

const handleUpdateComment = (updatedComment) => {
    const index = comments.value.findIndex(c => c.id === updatedComment.id);
    if (index > -1) {
        comments.value.splice(index, 1, updatedComment);
    }
};

const handleDeleteComment = (commentId) => {
    comments.value = comments.value.filter(c => c.id !== commentId);
    pagination.value.total -= 1;
};


watch(() => props.characterId, (newVal) => {
    if (newVal) {
        pagination.value.page = 1;
        loadComments();
    }
});

onMounted(() => {
    if (props.characterId) {
        loadComments();
    }
});
</script>

<style scoped>
.comment-list-container {
    position: relative;
    min-height: 300px;
}

.floating-action {
    position: fixed;
    right: 40px;
    bottom: 40px;
    width: 56px;
    height: 56px;
    background: var(--el-color-primary);
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transition: transform 0.2s;
    z-index: 2000;
}

.floating-action:hover {
    transform: scale(1.1);
}

.el-pagination {
    justify-content: center;
    margin: 20px 0;
    padding-bottom: 20px;
}

:deep(.el-empty__description) {
    margin-top: 20px;
}
</style>